package handlers

import (
	"net/http"
	"strings"
)

func joinUKeyErrors(errs []string) string {
	if len(errs) == 0 {
		return "UKey operation failed"
	}
	return strings.Join(errs, "; ")
}

func extractStringAt(arr []interface{}, idx int) string {
	if idx < 0 || idx >= len(arr) {
		return ""
	}
	if s, ok := arr[idx].(string); ok {
		return s
	}
	return ""
}

func httpStatusFromError(msg string) int {
	switch {
	case msg == "":
		return http.StatusOK
	case strings.Contains(msg, "communication error"):
		return http.StatusServiceUnavailable
	case strings.Contains(msg, "Customs submission failed"):
		return http.StatusBadGateway
	default:
		return http.StatusBadRequest
	}
}

// normalizePEMBody strips any PEM header/footer and whitespace, returning the base64 payload body.
func normalizePEMBody(pemOrB64 string) string {
	s := strings.TrimSpace(pemOrB64)
	s = strings.ReplaceAll(s, "\r", "")
	// If looks like PEM, strip any BEGIN/END lines regardless of type
	if strings.Contains(s, "-----BEGIN ") {
		var b strings.Builder
		for _, line := range strings.Split(s, "\n") {
			line = strings.TrimSpace(line)
			if line == "" || strings.HasPrefix(line, "-----BEGIN ") || strings.HasPrefix(line, "-----END ") {
				continue
			}
			b.WriteString(line)
		}
		return b.String()
	}
	// Likely already base64; drop all whitespace/newlines.
	return strings.ReplaceAll(strings.ReplaceAll(s, "\n", ""), " ", "")
}
